package com.tgpms.web.element.controller;

import cn.hutool.core.date.DateUtil;
import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.*;
import com.tgpms.util.PageInfo;
import com.tgpms.web.element.entity.CommodityMaster;
import com.tgpms.web.element.entity.TaggedEquipment;
import com.tgpms.web.element.service.ITaggedEquipmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jl
 * Created on 2020/7/10
 */
@Api(value = "TaggedEquipmentController", tags = "D1130设备总清单相关接口")
@RestController
@RequestMapping("/ev/taggedEquipment")
@Slf4j
public class TaggedEquipmentController {
    @Autowired
    private ITaggedEquipmentService service;
    @Resource
    private TokenService tokenService;

    /**
     * 查询设备总清单信息
     **/
    @ApiOperation(value = "查询设备总清单信息", notes = "查询设备总清单信息", httpMethod = "POST")
    @PostMapping(value = "/selTaggedEquipmentList")
    public Result selTaggedEquipmentList(@RequestParam(value = "selparam", required = false) String selparam,
                                         @RequestParam(value = "leftdition", required = false) String leftdition,
                                         @RequestParam(value = "condition", required = false) String condition,
                                         @RequestParam(value = "dataowner") String dataowner,
                                         @RequestParam(value = "pageNo", required = false, defaultValue = "1") String pageNo,
                                         @RequestParam(value = "pageSize", required = false, defaultValue = "10") String pageSize) {
        Result result = new Result();
        PageInfo pageInfo = new PageInfo();
        try {
            pageInfo.setPage(pageNo);
            pageInfo.setSize(pageSize);
            Map<String, String> map = new HashMap<String, String>();
            map.put("selparam", selparam);
            map.put("leftdition", leftdition);
            map.put("condition", condition);
            map.put("dataowner", dataowner);
            pageInfo.setQueryMap(map);
            result = service.selTaggedEquipmentList(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
            throw new QueryException(ExceptionExplain.ERROR_BY_QUERY.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "新增设备总清单信息", notes = "新增设备总清单信息", httpMethod = "POST")
    @PostMapping(value = "/addTaggedEquipmentInfo")
    public Result addTaggedEquipmentInfo(@RequestBody TaggedEquipment en, HttpServletRequest request) {
        Result result = new Result();
        try {
            String insertName = tokenService.getUserName(request);
            en.setInsertUser(insertName);
            en.setInsertDate(DateUtil.now());
            Map<String, String> map = service.addTaggedEquipmentInfo(en);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
                result.setData(map.get("data"));
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
            throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "修改设备总清单信息", notes = "修改设备总清单信息", httpMethod = "PUT")
    @PutMapping(value = "/updateTaggedEquipmentInfo")
    public Result updateTaggedEquipmentInfo(@RequestBody TaggedEquipment en, HttpServletRequest request) {
        Result result = new Result();
        if (en.getEqTagNo() == null) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
            return result;
        }
        try {
            //获取token操作人
            en.setModifyUser(tokenService.getUserName(request));
            en.setModifyDate(DateUtil.now());
            Map<String, String> map = service.updateTaggedEquipmentInfo(en);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
            throw new UpdateException(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
        }
        return result;
    }

    @ApiOperation(value = "删除设备总清单信息", notes = "删除设备总清单信息", httpMethod = "DELETE")
    @DeleteMapping(value = "/deleteTaggedEquipmentInfo")
    public Result deleteTaggedEquipmentInfo(@RequestParam(value = "eqTagNo") String eqTagNo) {
        Result result = new Result();
        if (StringUtils.isBlank(eqTagNo)) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
            return result;
        }
        try {
            Map<String, String> map = service.deleteTaggedEquipmentInfo(eqTagNo);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
            throw new DeleteException(ExceptionExplain.ERROR_BY_DELETE.getExplain());
        }
        return result;
    }

    /**
     * Excel批量导入
     */
    @ApiOperation(value = "Excel批量导入设备总清单信息接口", notes = "Excel批量导入设备总清单信息接口", httpMethod = "POST")
    @PostMapping("/import")
    public Result batchImport(@RequestParam("file") MultipartFile file,@RequestParam("project")String project, @RequestParam(value = "dataOwner") String dataOwner, HttpServletRequest request) {
        Result result = new Result();
        String insertName = tokenService.getUserName(request);
        try {
            Map<String, String> map = service.batchImport(file,project, dataOwner, insertName);
            if (map.get("code").equals("1")) {
                result.setSuccess(true);
                result.setData(map.get("data"));
            } else {
                result.setSuccess(false);
            }
            result.setMsg(map.get("info"));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
            throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
        }
        return result;
    }

    /**
     * 下载Excel模板
     */
    @ApiOperation(value = "下载设备总清单导入模板", notes = "下载设备总清单导入模板", httpMethod = "POST")
    @RequestMapping(value = "/downloadTemp", produces= MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void  downloadTemp(@RequestParam("fileName")String fileName, HttpServletResponse response) {
        //定义文件名
//        String fileName = "D1130设备总清单导入模板.xlsx";
        try {
            //获取资源文件
            ClassPathResource classPathResource = new ClassPathResource("static/"+fileName);
            //设置响应类型
            response.setCharacterEncoding("UTF-8");
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            response.setHeader("content-Type", type);
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //获取资源文件输入流和httpServletResponse的输出流
            try (InputStream inputStream =classPathResource.getInputStream(); ServletOutputStream servletOutputStream = response.getOutputStream()) {
                //把资源文件的二进制流数据copy到response的输出流中
                IOUtils.copy(inputStream, servletOutputStream);
                //清除flush所有的缓冲区中已设置的响应信息至客户端
                response.flushBuffer();
            } catch (Exception e) {
                //错误日志记录
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            //自定义业务异常
            throw new ProjectException("导出模板失败");
        }
    }

}
